<?php

include 'db.php';
include 'pricelist_functions.php';

$pl_id = $_POST[ 'pricelist_id' ];
$pl_name = $_POST[ 'pricelist_name' ];


//get base material prices
$corp_base_materials = array();
$show_corp_prices->bind_result( $base_name, $base_typeID, $base_price, $base_volume );
$show_corp_prices->execute();
while( $show_corp_prices->fetch() )
{
	$corp_base_materials[ $base_typeID ] = array('price' => $base_price, 'volume' => $base_volume);
}
$show_corp_prices->close();

//get pricelist data
//$pricelist_get_data = $db_corp->prepare( "SELECT pricelist_name, pricelist_last_update, markup_over_buildcost, replacement_discount, round_to, production_location_id FROM pricelists WHERE pricelist_ID = ?" );
$pricelist_get_data->bind_param( 'i', $pl_id );
$pricelist_get_data->bind_result( $pl_name, $pl_upd, $pl_markup, $pl_discount, $pl_round, $pl_loc_id );
$pricelist_get_data->execute();
$pricelist_get_data->fetch();
$pricelist_get_data->close();

//get facility data
$get_facility_by_id->bind_param( 'i', $pl_loc_id );
$get_facility_by_id->bind_result( $fac_name, $fac_mm, $fac_tm, $fac_ic, $fac_phc, $fac_type );
$get_facility_by_id->execute();
$get_facility_by_id->fetch();
$get_facility_by_id->close();

//get all the stuff from pricelist
$pricelist_get->bind_param( 'i', $pl_id );
$pricelist_get->bind_result( $prod_id, $item_id, $item_name, $item_build_cost, $item_price, $item_replacement, $item_mat_volume );
$pricelist_get->execute();

$stuff_to_upd = array();
while( $pricelist_get->fetch() )
{
	$result = get_item_production_cost( $item_id, $fac_mm, $fac_tm, $fac_ic, $fac_phc, $corp_base_materials );
	$result[ 'prod_id' ] = $prod_id;
	$stuff_to_upd[] = $result;
}
$pricelist_get->close();

//now update all the stuff
//$pricelist_update_data = $db_corp->prepare( "UPDATE pricelists_data SET build_cost = ?, price_new = ?, price_replacement = ?, materials_volume = ? WHERE product_ID = ?" );

$item_price = 0;
$item_replacement_price = 0;
$materials_volume = 0;
$build_cost = 0;
$prod_id = 0;
$pricelist_update_data->bind_param( 'ddddi', $build_cost, $item_price, $item_replacement_price, $materials_volume, $prod_id);
foreach( $stuff_to_upd as $stuff )
{
	$prod_id = $stuff[ 'prod_id' ];
	$build_cost = $stuff[ 'build_cost' ];
	$item_price = ceiling(  $build_cost * (1 + $pl_markup/100), $pl_round );
	$item_replacement_price = ceiling( $item_price * ( 1 - $pl_discount / 100), $pl_round );
	$materials_volume = $stuff[ 'materials_volume' ];
	$pricelist_update_data->execute();
}
$pricelist_update_data->close();

//we need to update materials too
$pricelist_materials_data->bind_param( 'iii', $prod_id, $mat_id, $mat_count );
foreach( $stuff_to_upd as $stuff )
{
	$prod_id = $stuff[ 'prod_id' ];
	foreach( $stuff['materials'] as $mat_id => $mat_count )
	{
		$pricelist_materials_data->execute();
	}
}
$pricelist_materials_data->close();



include 'display_pricelist.php';

?>